import { _decorator, Animation, AnimationClip } from 'cc';
import State from '../../Base/State';
import StateMachine, { getInitParamsTrigger } from '../../Base/StateMachine';
import { EntityTypeEnum } from '../../Common';
import { EntityStateEnum, ParamsNameEnum } from '../../Enum';
import { WeaponManager } from './WeaponManager';
const { ccclass } = _decorator;

@ccclass('WeaponStateMachine')
export class WeaponStateMachine extends StateMachine {
  init(type: EntityTypeEnum) {
    this.type = type;
    this.animationComponent = this.node.addComponent(Animation);
    this.initParams();
    this.initStateMachines();
    this.initAnimationEvent()
  }

  // 参数状态集合中添加 idle状态 Attack状态
  initParams() {
    this.params.set(ParamsNameEnum.Idle, getInitParamsTrigger());
    this.params.set(ParamsNameEnum.Attack, getInitParamsTrigger());
  }

  // 状态机集合中添加 idle状态动画&&Attack状态动画
  initStateMachines() {
    this.stateMachines.set(
      ParamsNameEnum.Idle,
      new State(
        this,
        `${this.type}${EntityStateEnum.Idle}`,
        AnimationClip.WrapMode.Loop,
      ),
    );
    this.stateMachines.set(
      ParamsNameEnum.Attack,
      new State(
        this,
        `${this.type}${EntityStateEnum.Attack}`,
        AnimationClip.WrapMode.Normal,
        true
      ),
    );
  }

  initAnimationEvent(){
    this.animationComponent.on(
      Animation.EventType.FINISHED,
      () => {
        // 攻击动画播放完毕后，恢复到默认状态
        if(this.animationComponent.defaultClip.name.includes(EntityStateEnum.Attack)){
          this.node.parent.getComponent(WeaponManager).state=EntityStateEnum.Idle
        }
      },
      this,
    );
  }

  // 将当前状态同步到currentState
  run() {
    switch (this.currentState) {
      case this.stateMachines.get(ParamsNameEnum.Idle):
      case this.stateMachines.get(ParamsNameEnum.Attack):
        if (this.params.get(ParamsNameEnum.Attack).value) {
          this.currentState = this.stateMachines.get(ParamsNameEnum.Attack);
        } else if (this.params.get(ParamsNameEnum.Idle).value) {
          this.currentState = this.stateMachines.get(ParamsNameEnum.Idle);
        } else {
          this.currentState = this.currentState;
        }
        break;
      default:
        this.currentState = this.stateMachines.get(ParamsNameEnum.Idle);
        break;
    }
  }
}
